import axios from "axios";

// 不需要添加Authorization头的API路径
const publicApiPaths = [
  '/api/Mange/GetCaptcha/captcha',
  '/api/Mange/RefreshCaptcha/captcha/refresh',
  '/api/Mange/VerifyCaptcha/captcha/verify',
  '/api/Captcha/generate',
  '/api/Captcha/verify',
  '/api/Mange/LoginUser',
  '/api/Mange/RegisterUser/register'
];

// 检查是否为公开API
const isPublicApi = (url: string | undefined): boolean => {
  if (!url) return false;
  return publicApiPaths.some(path => url.includes(path));
};

const apiWreit = axios.create({
  baseURL: 'http://localhost:34405',
  timeout: 15000, // 增加到15秒
});

// 添加请求拦截器
apiWreit.interceptors.request.use(function (config) {
  // 检查是否为公开API
  if (isPublicApi(config.url)) {
    console.log(`公开API请求: ${config.url}`);
    return config;
  }
  
  // 从localStorage获取token
  const token = localStorage.getItem('token');
  
  // 如果存在token，则添加到请求头中
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 重试配置
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; // 1秒

// 重试函数
const retryRequest = (error: any, retryCount = 0): Promise<any> => {
  if (retryCount >= MAX_RETRIES) {
    return Promise.reject(error);
  }

  // 只对网络错误和超时错误进行重试
  if (error.code === 'ECONNABORTED' || error.code === 'NETWORK_ERROR' ||
      (error.response && error.response.status >= 500)) {
    console.log(`请求失败，正在进行第 ${retryCount + 1} 次重试...`);

    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(apiWreit.request(error.config));
      }, RETRY_DELAY * (retryCount + 1)); // 递增延迟
    }).catch((retryError) => {
      return retryRequest(retryError, retryCount + 1);
    });
  }

  return Promise.reject(error);
};

// 添加响应拦截器
apiWreit.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  console.error('请求失败:', error);

  // 如果是401错误，可能是token过期或无效
  if (error.response && error.response.status === 401) {
    console.warn('收到401未授权响应，可能是令牌已过期');
    // 清除token
    localStorage.removeItem('token');
    return Promise.reject(error);
  }

  // 对于超时和网络错误，尝试重试
  if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
    console.warn('请求超时，尝试重试...');
    return retryRequest(error);
  }

  if (error.code === 'NETWORK_ERROR' || !error.response) {
    console.warn('网络错误，尝试重试...');
    return retryRequest(error);
  }

  return Promise.reject(error);
});

export {apiWreit};